<!--报表管理 - ppm报表-->
<template>
  <basic-container>
    <el-tabs type="border-card" class="tab-font">
      <el-tab-pane label="PPM搜索"> </el-tab-pane>
      <avue-form ref="form" :option="option" v-model="form">
        <template slot="btn">
          <el-button type="primary" size="small" class="el-icon-search" @click="handleSubmit">搜索</el-button>
          <el-button size="small" class="el-icon-delete" @click="handleCancel">清空</el-button>
        </template>
      </avue-form>
    </el-tabs>
    <el-tabs type="border-card" class="chart-tab tab-font">
      <el-tab-pane label="PPM明细"> </el-tab-pane>
      <div class="chart-header">
        <el-select class="workshopSelect" v-model="search.workshopName" placeholder="请选择车间" @change="workshopChange">
          <el-option v-for="item in search.workshopList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <div class="time">时间:{{ `${params.startDate} - ${params.endDate}` }}</div>
      </div>
      <el-row :gutter="20">
        <el-col :span="24">
          <chart-view class="chart-content" :chart-option="chartOption" :auto-resize="true" width="100%" />
          <avue-crud :option="tableOption" :table-loading="loading" :data="data" :page="tablePage" @current-change="currentChange" @size-change="sizeChange" ref="crud">
            <template slot="menuLeft"> <el-button type="warning" size="small" icon="el-icon-download" @click="$refs.exportExcel.visible = true">导出</el-button></template>
          </avue-crud>
        </el-col>
      </el-row>
    </el-tabs>
    <export-excel
      ref="exportExcel"
      url="/api/mes-abacus/statProductionDay/export-workshop-ppm"
      name="PPM"
      :option="tableOption"
      :page="tablePage"
      :query="params"
    ></export-excel>
  </basic-container>
</template>

<script>
import ChartView from '@/components/chart/index.vue';
import moment from 'moment';
import { getWorkshop } from '@/api/aps/planEnact';
import { tableOption, option } from '@/views/report/workshopPPM.js';
import { getWorkshopppmList, getWorkshopppmPage } from '@/api/report/report';
import exportExcel from '@/components/export-excel/exp.vue';

export default {
  name: 'workshopPPM',
  components: {
    ChartView,
    exportExcel
  },
  data() {
    return {
      search: {
        workshopName: '',
        workshopList: []
      },
      params: {
        startDate: '',
        endDate: '',
        workshopName: '',
        statisticsTimeDimension: 'DAY'
      },
      form: {
        examineDate: this.getDefaultTime()
      },
      loading: false,
      data: [],
      tableOption,
      tablePage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      option,
      chartOption: {
        title: {
          text: 'PPM趋势图',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
          // formatter: '{a0}: {c0}<br />{a1}: {c1}%'
        },
        legend: {
          top: '10%',
          tooltip: {
            show: true
            // formatter: function ({ name }) {
            //   return name === '直通率' ? 'PPM为所有生产该产品的工单直通率的平均值' : '产量';
            // }
          }
        },
        xAxis: {
          type: 'category',
          axisLabel: {
            rotate: 30
          },
          boundaryGap: false,
          data: [],
          name: '日期'
        },
        yAxis: [
          {
            type: 'value',
            axisLabel: {
              formatter: '{value}'
            },
            nameTextStyle: {
              // fontWeight: 'bold',
              // fontSize: 16
              // padding: [0, 60, 20, 0]
            },
            name: 'PPM'
            // nameLocation: 'start'
          }
        ],
        series: [
          {
            // name: 'PPM',
            type: 'line',
            data: [],
            color: ['#02a7f0']
          }
        ]
      }
    };
  },
  mounted() {
    let defaultStartTime = this.$moment(new Date()).subtract(29, 'days').format('yyyy-MM-DD');
    let defaultEndTime = this.$moment(new Date()).subtract(0, 'days').format('yyyy-MM-DD');
    console.log('this.params', this.params);
    this.params.startDate = defaultStartTime;
    this.params.endDate = defaultEndTime;
    getWorkshop()
      .then((res) => {
        let data = res.data.data;
        this.search.workshopList = data.map((d) => {
          return {
            label: d.workshopName,
            value: d.workshopName
          };
        });
        console.log('data', data);
      })
      .catch((err) => {});
  },
  methods: {
    workshopChange(value) {
      this.chartOption.title.text = value + 'PPM趋势图';
      this.getChartData(value);
    },
    onLoad() {
      if (this.form.statisticsTimeDimension == 'DAY') {
        this.params.startDate = this.form.examineDate[0];
        this.params.endDate = this.form.examineDate[1];
        this.params.workshopName = this.form.workshopName;
      } else {
        // 获取当年当月有多少天
        this.params.startDate = this.form.month[0];
        this.params.endDate = this.form.month[1];
        this.params.workshopName = this.form.workshopName;

        let nowYear = new Date().getFullYear();
        let nowMonth = new Date().getMonth() + 1;
        let nowDate = new Date().getDate();
        let endYear = this.form.month[1].split('-')[0];
        let startMonth = this.form.month[0].split('-')[1];
        let endMonth = this.form.month[1].split('-')[1];
        let endDays = new Date(endYear, endMonth, 0).getDate();
        if (endYear > nowYear || (endYear == nowYear && endMonth >= nowMonth && startMonth <= nowMonth)) {
          if (nowMonth < 10) {
            nowMonth = '0' + nowMonth;
          }
          if (nowDate < 10) {
            nowDate = '0' + nowDate;
          }
          this.params.endDate = nowYear + '-' + nowMonth + '-' + nowDate;
        } else {
          this.params.endDate = endYear + '-' + endMonth + '-' + endDays;
        }
        this.params.statisticsTimeDimension = this.form.statisticsTimeDimension;
        console.log('this.params', this.params);
      }

      this.loading = true;
      getWorkshopppmPage(this.tablePage.currentPage, this.tablePage.pageSize, this.form.statisticsTimeDimension, this.params)
        .then((res) => {
          let data = res.data.data;
          this.data = data.records || [];
          this.tablePage.total = data.total;
          if (this.data.length > 0) {
            this.search.workshopName = this.data[0].workshopName;
            this.chartOption.title.text = this.data[0].workshopName + 'PPM趋势图';
          } else {
            this.chartOption.title.text = this.form.workshopName + 'PPM趋势图';
          }
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    getChartData(name) {
      getWorkshopppmList({
        endDate: this.params.endDate,
        startDate: this.params.startDate,
        statisticsTimeDimension: this.form.statisticsTimeDimension,
        workshopName: name
      })
        .then((res) => {
          let data = res.data.data;
          this.setChartOption(data);
        })
        .catch((err) => {});
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad();
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad();
    },
    setChartOption(data) {
      const xAxisData = data.xData;
      const yieldData = data.series;
      const series = [
        {
          name: 'PPM',
          type: 'line',
          data: yieldData,
          color: ['#02a7f0']
        }
      ];
      const xAxis = {
        type: 'category',
        boundaryGap: false,
        data: xAxisData,
        axisLabel: {
          rotate: 30
        }
      };
      this.$set(this.chartOption, 'xAxis', xAxis);
      this.$set(this.chartOption, 'series', series);
    },
    handleSubmit() {
      this.$refs.form.validate((valid, done) => {
        if (valid) {
          this.onLoad();
          this.getChartData(this.form.workshopName);
          done();
        }
      });
    },
    handleCancel() {
      this.$nextTick(() => {
        this.data = [];
        this.search.workshopName = '';
        this.tablePage.total = 0;
        this.tablePage.currentPage = 1;
        this.tablePage.pageSize = 15;
        this.chartOption.title.text = 'PPM趋势图';
        this.params.startDate = '';
        this.params.endDate = '';
        this.params.workshopName = '';
        this.params.statisticsTimeDimension = 'DAY';
      });
      const series = this.chartOption.series.map((item) => ({ ...item, data: [] }));
      this.$refs.form.resetForm();
      this.form.statisticsTimeDimension = 'DAY';
      this.$set(this.chartOption, 'series', series);
    },
    getDefaultTime() {
      let defaultStartTime = this.$moment(new Date()).subtract(29, 'days').format('yyyy-MM-DD');
      let defaultEndTime = this.$moment(new Date()).subtract(0, 'days').format('yyyy-MM-DD');
      return [defaultStartTime, defaultEndTime];
    }
  }
};
</script>

<style scoped lang="scss">
.chart-tab {
  margin-top: 24px;
  height: calc(100vh - 350px);
  overflow-y: scroll;
}
.chart-header {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px;
  .workshopSelect {
    position: absolute;
    right: 100px;
  }
}
.tab-font {
  ::v-deep .el-tabs__item {
    color: #606266 !important;
    font-weight: bold;
  }
}
</style>
